package com.android.support.lib.universal.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.android.support.lib.universal.general.GeneralCache;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

/**
 * 文件操作
 * 
 * @author 彭治铭
 *
 */
public class Utilimg {
	// 文件路径
	public final String HEAD_PATH = GeneralCache.getCacleImg()
			.getAbsolutePath();

	/**
	 * 创建一个以userId为文件名的文件，保存用户头像。文件路径为"/sdcard/woliao/selfId/friendId.jpg"
	 * 
	 * @param selfId
	 * @param friendId
	 * @return
	 */
	public File createFile(String selfId, String friendId) {
		String filePath = Environment.getExternalStorageDirectory()
				+ "/woliao/" + selfId;
		File fileParent = new File(filePath);
		if (fileParent.exists() == false) {
			fileParent.mkdirs();
		}

		File file = new File(filePath + "/" + friendId + ".jpg");
		try {
			file.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return file;
	}

	/**
	 * 根据fileType,创建普通的jpg或3gp文件来保存图片或语音
	 * 
	 * @param selfId
	 * @param fileType
	 * @return
	 */
	public File createFile(String selfId, int fileType) {
		String nowTime = new Utiltime().getAbsoluteTime(null);
		String filePath = Environment.getExternalStorageDirectory()
				+ "/woliao/" + selfId;
		File fileParent = new File(filePath);
		if (fileParent.exists() == false) {
			fileParent.mkdirs();
		}
		File file = null;
		if (fileType == Config.MESSAGE_TYPE_IMG) {
			file = new File(filePath + "/" + nowTime + ".jpg");
		} else if (fileType == Config.MESSAGE_TYPE_AUDIO) {
			file = new File(filePath + "/" + nowTime + ".3gp");
		}

		try {
			file.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Log.i("FileUtil", "createFile file" + file);
		return file;
	}

	/**
	 * 将Uri图片的内容复制到file上,成功返回true
	 * 
	 * @param cr
	 *            this.getContentResolver()
	 * @param file
	 * @param uri
	 * @param photoPath
	 *            相册图片路径，解决图像选择问题,可以为null
	 * @return
	 */
	public boolean writeFile(ContentResolver cr, File file, Uri uri,
			String photoPath) {
		boolean result = true;
		try {
			FileOutputStream fout = new FileOutputStream(file);
			Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));

			int bitmapWidth = bitmap.getWidth();
			int bitmapHeight = bitmap.getHeight();
			// 缩放图片的尺寸比例
			float scale = (float) 158 / bitmapWidth;
			Matrix matrix = new Matrix();
			matrix.postScale(scale, scale);
			// 产生缩放后的Bitmap对象
			bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth,
					bitmapHeight, matrix, false);
			if (photoPath != null && !photoPath.equals("")) {
				try {
					// 处理图片旋转问题
					bitmap = rotateBitmap(photoPath, bitmap);
				} catch (Exception e) {
					// TODO: handle exception
					Log.e("test", "writeFile图片选择异常" + e.getMessage());
				}

			}
			// 压缩图片，并且保存文件
			bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fout);// 80是压缩率，表示压缩20%;取值范围在0~100，代表质量

			try {
				fout.flush();
				fout.close();
			} catch (IOException e) {
				e.printStackTrace();
				result = false;
			}
		} catch (FileNotFoundException e) {
			Log.e("test", "相册图片异常1" + e.getMessage());
			result = false;
		} catch (Exception e) {
			Log.e("test", "相册图片异常2" + e.getMessage());
		}

		return result;
	}

	/**
	 * 获取相册图片路径
	 * 
	 * @param data
	 *            onActivityResult参数中的Intent data对象。
	 * @return
	 */
	public String getPhotoPath(Activity activtiy, Intent data) {
		String photoPath = null;
		try {
			Uri uri = data.getData();
			// 获取相册图片路径
			String[] proj = { MediaStore.Images.Media.DATA };
			// 好像是android多媒体数据库的封装接口，具体的看Android文档
			Cursor cursor = activtiy.managedQuery(uri, proj, null, null, null);
			// 按我个人理解 这个是获得用户选择的图片的索引值
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			// 将光标移至开头 ，这个很重要，不小心很容易引起越界
			cursor.moveToFirst();
			// 最后根据索引值获取图片路径
			photoPath = cursor.getString(column_index);
			// bm = BitmapFactory.decodeFile(path);
		} catch (Exception e) {
			// TODO: handle exception
			Log.e("test", "相册图片路径获取失败" + e.getMessage());
		}
		return photoPath;
	}

	/**
	 * 获取压缩图片，并且保存该压缩图片到本地文件。
	 * 
	 * @param path
	 *            图片路径
	 * @param bm
	 *            位图图像
	 * @param width
	 *            压缩后的宽带。高度会根据宽带，按比例压缩。
	 * @param quality
	 *            压缩质量,(0~100) 数值越小质量越差。100质量等价与原图。
	 * @return
	 */
	public Bitmap getScaleBitmap(String path, Bitmap bm, float width,
			int quality) {
		bm = BitmapFactory.decodeFile(path);
		try {
			int bitmapWidth = bm.getWidth();
			int bitmapHeight = bm.getHeight();
			// 缩放图片的尺寸比例
			float scale = (float) width / bitmapWidth;
			Matrix matrix = new Matrix();
			matrix.postScale(scale, scale);
			// 产生缩放后的Bitmap对象
			bm = Bitmap.createBitmap(bm, 0, 0, bitmapWidth, bitmapHeight,
					matrix, false);
			File myCaptureFile = new File(path);
			FileOutputStream out = new FileOutputStream(myCaptureFile);
			// 压缩图片，并且保存文件
			bm.compress(Bitmap.CompressFormat.JPEG, quality, out);// 30是压缩率，表示压缩70%;取值范围在0~100，代表质量
		} catch (Exception e) {
			// TODO: handle exception
		}
		return bm;
	}

	/**
	 * 处理相册中的图片旋转问题
	 * 
	 * @param path
	 *            文件路径,必须是指定文件的路径
	 * @param bitmap
	 *            位图
	 * @return
	 */
	public Bitmap rotateBitmap(String path, Bitmap bitmap) {
		int degree = readPictureDegree(path);
		return rotateBitmap(bitmap, degree);
	}

	private int readPictureDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

	private Bitmap rotateBitmap(Bitmap bitmap, int rotate) {
		if (bitmap == null)
			return null;

		int w = bitmap.getWidth();
		int h = bitmap.getHeight();

		// Setting post rotate to 90
		Matrix mtx = new Matrix();
		mtx.postRotate(rotate);
		return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
	}

	/**
	 * 根据用户ID,创建一个以该ID为文件名的jpg图片
	 * 
	 * @param userId
	 * @return
	 */
	public File createHeadFile(String userId) {
		File fileParent = new File(HEAD_PATH);
		if (fileParent.exists() == false) {
			fileParent.mkdirs();
		}

		File file = null;
		file = new File(HEAD_PATH + "/" + userId + ".jpg");
		if (file.exists() == false) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return file;
	}

	/**
	 * 根据ID获取图片
	 * 
	 * @param userId
	 * @return
	 */
	public Bitmap getHeadFile(int userId) {
		File file = new File(HEAD_PATH + "/" + userId + ".jpg");
		if (file.exists() == false) {
			return null;
		}

		Bitmap bitmap = BitmapFactory.decodeFile(HEAD_PATH + "/" + userId
				+ ".jpg");
		return bitmap;
	}

	public interface Config {
		public final int MESSAGE_TYPE_IMG = 1;
		public final int MESSAGE_TYPE_AUDIO = 2;

	}
}
